<?php

/**
 * 
 * ClientEngage: ClientEngage Visitor Voice (http://www.clientengage.com)
 * Copyright 2012, ClientEngage (http://www.clientengage.com)
 *
 * You must have purchased a valid license from CodeCanyon in order to have 
 * the permission to use this file.
 * 
 * You may only use this file according to the respective licensing terms 
 * you agreed to when purchasing this item on CodeCanyon.
 * 
 * 
 * 
 *
 * @author          ClientEngage <contact@clientengage.com>
 * @copyright       Copyright 2013, ClientEngage (http://www.clientengage.com)
 * @link            http://www.clientengage.com ClientEngage
 * @since           ClientEngage - Visitor Voice v 1.0
 * 
 */
App::uses('AppModel', 'Model');

/**
 * Visitorform Model
 *
 * @property Field $Field
 * @property NotificationUser $NotificationUser
 * @property Visitorvoice $Visitorvoice
 */
class Visitorform extends AppModel
{

    public $name = 'Visitorform';

    /**
     * Display field
     *
     * @var string
     */
    public $displayField = 'title';

    /**
     * Behaviours to be loaded
     * @var array
     */
    public $actsAs = array('Utility.Sluggable');

    /**
     * Sets the global order of all Visitorform queries
     * @var string 
     */
    public $order = 'Visitorform.created DESC';

    /**
     * Validation rules
     *
     * @var array
     */
    public $validate = array(
        'title' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Please enter a title.',
            ),
            'maxlength' => array(
                'rule' => array('maxLength', 250),
                'message' => 'The title may not exceed 250 characters.'
            )
        ),
        'buttontheme_id' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Please select a Button Theme',
            ),
        ),
        'formtheme_id' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Please select a Form Theme',
            ),
        ),
        'slug' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Please enter a valid Url segment.'
            ),
            'unique' => array(
                'rule' => 'isUnique',
                'message' => 'This URL has already been taken'
            ),
            'validslug' => array(
                'rule' => '/^[a-z0-9-_]+$/',
                'message' => 'Please enter a valid Url segment.'
            )
        ),
        'error_message' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Please enter your error message.',
            ),
        ),
        'active' => array(
            'boolean' => array(
                'rule' => array('boolean'),
                'message' => 'Please enter a valid boolean value.',
            ),
        ),
        'archived' => array(
            'boolean' => array(
                'rule' => array('boolean'),
                'message' => 'Please enter a valid boolean value.',
            ),
        ),
        'visitorvoice_count' => array(
            'numeric' => array(
                'rule' => array('numeric'),
                'message' => 'Pelase enter a valid integer.',
            ),
        ),
        'modal_width' => array(
            'validcsslength' => array(
                'rule' => array('custom', '^[+-]?[0-9]+\.?([0-9]+)?(px|em|ex|%|in|cm|mm|pt|pc)$^'),
                'message' => 'Please enter a valid CSS width/height (e.g. in px/em/%).',
            ),
        ),
        'modal_height' => array(
            'validcsslength' => array(
                'rule' => array('custom', '^[+-]?[0-9]+\.?([0-9]+)?(px|em|ex|%|in|cm|mm|pt|pc)$^'),
                'message' => 'Please enter a valid CSS width/height (e.g. in px/em/%).',
            ),
        ),
    );

    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'Formtheme' => array(
            'className' => 'Formtheme',
            'foreignKey' => 'formtheme_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Buttontheme' => array(
            'className' => 'Buttontheme',
            'foreignKey' => 'buttontheme_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
    );

    /**
     * hasMany associations
     *
     * @var array
     */
    public $hasMany = array(
        'Field' => array(
            'className' => 'Field',
            'foreignKey' => 'visitorform_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => 'Field.position ASC',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
        'Visitorvoice' => array(
            'className' => 'Visitorvoice',
            'foreignKey' => 'visitorform_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

    public function beforeFind($queryData)
    {
        $conditions = array();
        $mergedQuery = Set::merge($conditions, $queryData);
        return parent::beforeFind($mergedQuery);
    }

    public function afterSave($created)
    {
        $this->deleteFormCaches($this->id);
        parent::afterSave($created);
    }

    public function afterDelete()
    {
        $this->deleteFormCaches($this->id);
        parent::afterDelete();
    }

    /**
     * Deletes the caches of the passed visitorform
     * @param uuid $id
     * @param bool $deleteResponseCache Indicates whether to also delete
     * the entire cache of individual visitorvoices (neccessitates) re-caching
     */
    public function deleteFormCaches($id, $deleteResponseCache = false)
    {
        $formCacheKey = 'Visitorform_' . md5($id);
        $statsCacheKey = 'Statistics_' . md5($id);
        $fullTableCacheKey = 'FullTable_' . md5($id);

        Cache::delete($formCacheKey);
        Cache::delete($statsCacheKey);
        Cache::delete($fullTableCacheKey);

        if ($deleteResponseCache)
            $this->Visitorvoice->deleteFormResponseCache($id);
    }

    /**
     * Duplicates the passed visitorform including all of its fields
     * @param uuid $id The visitorform's ID
     * @return bool Success
     * @throws NotFoundException
     */
    public function duplicate($id = null)
    {
        if (!($visitorform = $this->find('first', array(
            'conditions' => array('Visitorform.id' => $id),
            'contain' => array('Field' => 'FieldOption')))))
        {
            throw new NotFoundException(__('Invalid Visitor Form'));
        }

        unset($visitorform['Visitorform']['id']);
        unset($visitorform['Visitorform']['slug']);
        unset($visitorform['Visitorform']['created']);
        unset($visitorform['Visitorform']['modified']);
        unset($visitorform['Visitorform']['visitorvoice_count']);
        $visitorform['Visitorform']['title'] .= __('_Copy');
        $visitorform['Visitorform']['archived'] = false;
        $visitorform['Visitorform']['active'] = false;

        $visitorform = Hash::remove($visitorform, 'Field.{n}.id');
        $visitorform = Hash::remove($visitorform, 'Field.{n}.visitorform_id');
        $visitorform = Hash::remove($visitorform, 'Field.{n}.created');
        $visitorform = Hash::remove($visitorform, 'Field.{n}.modified');
        $visitorform = Hash::remove($visitorform, 'Field.{n}.FieldOption.{n}.id');
        $visitorform = Hash::remove($visitorform, 'Field.{n}.FieldOption.{n}.field_id');
        $visitorform = Hash::remove($visitorform, 'Field.{n}.FieldOption.{n}.created');
        $visitorform = Hash::remove($visitorform, 'Field.{n}.FieldOption.{n}.modified');

        return $this->saveAll($visitorform);
    }

}